package ltd.dujiabao.reserver.service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.reserver.constant.RequestHeaderConstant;
import ltd.dujiabao.reserver.domain.UploadResult;
import ltd.dujiabao.reserver.util.HttpClientUtils;
import ltd.dujiabao.reserver.util.JsonUtils;
import ltd.dujiabao.reserver.util.StringUtils;

/**
 * @author : DuJiabao
 * @Project : reserver
 * @Time : 2021/11/6 9:43
 * @Desc : 上传文件到指定的地址
 */

@Slf4j
@Service
public class UploadService {
    @Value("${reserver.upload.url}")
    public String uploadUrl;

    /**
     * 记住当前尝试上传图片次数
     */
    private static int count = 1;

    public static void resetUploadCount() {
        count = 1;
    }

    /**
     * @param cookie cookie
     * @param path   本地文件路径
     * @return 文件上传之后的文件名，用于提交预约表单使用
     */
    public String doUploadJpg(String cookie, String path) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        headers = buildHeaders(headers);
        HttpEntity requestEntity = buildEntity(path);

        HttpResponse response = HttpClientUtils.doPost(uploadUrl, headers, requestEntity);
        if (response != null) {
            try {
                String entity = EntityUtils.toString(response.getEntity());
                UploadResult uploadResult = JsonUtils.json2bean(entity, UploadResult.class);
                if (uploadResult.getResult()) {
                    log.info("Uploading file to system successfully, uploadResult: {}", uploadResult);
                    return uploadResult.getFilename();
                }
                log.warn("Uploading file to system fail, uploadResult: {}", uploadResult);
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 根据本地文件，构造一个MultipartEntity
     *
     * @param filePath 本地文件路径
     * @return MultipartEntity
     */
    private static HttpEntity buildEntity(String filePath) {
        if (StringUtils.isNullOrEmpty(filePath)) {
            log.warn("The input file path is null or empty.");
            return null;
        }
        String fileName = Paths.get(filePath).getFileName().toString();
        File file = new File(filePath);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        try {
            builder.addPart("id", new StringBody("WU_FILE_" + (count++), StandardCharsets.UTF_8))
                    .addPart("name", new StringBody(fileName, StandardCharsets.UTF_8))
                    .addPart("type", new StringBody("image/jpeg", StandardCharsets.UTF_8))
                    .addPart("file", new FileBody(file, ContentType.IMAGE_JPEG));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return builder.build();
    }

    /**
     * 构造一个header组成的map
     *
     * @param originHeaders 初始map
     * @return 返回增加了多个header之后的map
     */
    private static Map<String, String> buildHeaders(Map<String, String> originHeaders) {
        if (originHeaders == null) {
            originHeaders = new HashMap<>(10);
        }

        //headers.put("Host", "libyy.utsz.edu.cn");
        originHeaders.put(RequestHeaderConstant.HEADER_NAME_CONNECTION, "keep-alive");
        originHeaders.put(RequestHeaderConstant.HEADER_NAME_ORIGIN, "https://libyy.utsz.edu.cn");
        originHeaders.put(RequestHeaderConstant.HEADER_NAME_USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400");
        originHeaders.put(RequestHeaderConstant.HEADER_NAME_ACCEPT, "*/*");
        originHeaders.put(RequestHeaderConstant.HEADER_NAME_REFERER, "https://libyy.utsz.edu.cn/member/booking-in/index.html");
        originHeaders.put(RequestHeaderConstant.HEADER_NAME_ACCEPT_ENCODING, "gzip, deflate, br");
        originHeaders.put(RequestHeaderConstant.HEADER_NAME_ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9");
        return originHeaders;
    }
}
